function $(str) {
    return document.querySelector(str);
}

function $$(str) {
    return document.querySelectorAll(str);
}

function switch_tab(num) {
    var toolbox = $(".toolbox");
    var width = toolbox.clientWidth;
    toolbox.scrollLeft = width * num;
}

function goto(href) {
    window.location.href = href;
}

function alertWindow(html,f){
	var modal = document.createElement("div");
	modal.id = "modal";
	modal.style.position = "fixed";
	modal.style.left = "0";
	modal.style.top = "0";
	modal.style.right = "0";
	modal.style.bottom = "0";
	modal.style.backgroundColor = "rgba(0,0,0,0.5)";
	modal.style.zIndex = "9999";
	document.body.appendChild(modal);
	var box = document.createElement("div");
	box.style.width = "300px";
	box.style.backgroundColor = "white";
	box.style.borderRadius = "20px";
	box.style.position = "absolute";
	box.style.top = "50%";
	box.style.left = "0";
	box.style.right = "0";
	box.style.marginLeft = "auto";
	box.style.marginRight = "auto";
	var inner = document.createElement("div");
	inner.innerHTML = 
	html + 	"<br>\
	<div onclick='window.close_box(1)' style='width:40%;height:30px;background-color:lightskyblue;color:white;border-radius:25px; text-align:center;display:inline-block;cursor:pointer;'>确定</div>\
	<div onclick='window.close_box(0)' style='width:40%;height:30px;background-color:gray;color:white;border-radius:25px; text-align:center;display:inline-block;float:right;cursor:pointer;'>取消</div>"
	box.style.padding = "30px";
	box.style.boxSizing = "content-box";
	box.appendChild(inner);
	modal.appendChild(box);
	box.style.marginTop = -box.offsetHeight / 2 + "px";
	window.close_box = (n) => {
	    if(n==1){
			f();
		}
	    document.body.removeChild($("#modal"));
	    window.has_modal=false;
	};
}

function prompt(title, text, f) {
    var html="\
	<h4>{head}</h4>\
	<p>{inner}</p>\
	<input type='text' id='prompt-input' style='width:100%;border-radius:10px;'>\
	"
	.replace("{head}", title)
	.replace("{inner}", text);
	function callback(){
		var value = $("#prompt-input").value;
		f(value);
	}
	alertWindow(html,callback);
}

function tip(text,type='error',title='错误:') {
    var classes={
        error:'alert-danger',
        success:'alert-success',
        info:'alert-info',
        warning:'alert-warning'
    }
    var html = '<div class="alert '+classes[type]+ ' alert-dismissible fade show" style="position:absolute;width:400px;">'+
    "    <strong>"+title+"</strong>{tip}"+
    "</div>";
    $('.tip-box').innerHTML += format(html, { tip: text });
    $('.tip-box').style.zIndex = '1';
    setTimeout(() => {
        var el = $('.tip-box').children[$('.tip-box').children.length - 1];
        el.parentNode.removeChild(el);
        $('.tip-box').style.zIndex = '-1';
    }, 2000);
}

function rgbToHex(str) {
    str = str.replace(/\s/g, '');
    var first_d = str.indexOf(',');
    var second_d = str.indexOf(',', first_d + 1);
    var left_kh = str.indexOf('(');
    var right_kh = str.indexOf(')');
    var r = parseInt(str.slice(left_kh + 1, first_d));
    var g = parseInt(str.slice(first_d + 1, second_d));
    var b = parseInt(str.slice(second_d + 1, right_kh));
    var hex_str = "#";
    if (r < 16) hex_str += "0";
    hex_str += r.toString(16);
    if (g < 16) hex_str += "0";
    hex_str += g.toString(16);
    if (b < 16) hex_str += "0";
    hex_str += b.toString(16);
    if (hex_str == "#NaNNaNNaN") return "#000000";
    return hex_str;
}

function format(str, dict) {
    for (var d in dict) {
        str = str.replace(new RegExp("{" + d + "}", 'g'), dict[d]);
    }
    return str;
}

function hide_all_attrtab() {
    for (var i = 0; i < attrtabshow["all"].length; i++) {
        $("." + attrtabshow["all"][i]).style.display = "none";
    }
}

function getType(obj) {
    //tostring会返回对应不同的标签的构造函数
    var toString = Object.prototype.toString;
    var map = {
        '[object Boolean]': 'boolean',
        '[object Number]': 'number',
        '[object String]': 'string',
        '[object Function]': 'function',
        '[object Array]': 'array',
        '[object Date]': 'date',
        '[object RegExp]': 'regExp',
        '[object Undefined]': 'undefined',
        '[object Null]': 'null',
        '[object Object]': 'object'
    };
    if (obj instanceof Element) {
        return 'element';
    }
    return map[toString.call(obj)];
}

function keyboard_init(){
    window.addEventListener('keyup',(e)=>{
        if(e.keyCode==46){  //delete
            delete_element();
        }
    });
    window.addEventListener('keyup',(e)=>{
        if(e.keyCode>=112&&e.keyCode<=116){  //1-5
            switch_tab(e.keyCode-112); //转换到数字切换
        }
    });
}

function size_init(){
    window.onresize=()=>{
        $(".box").style.height=window.innerHeight-$('.toolbox').offsetHeight+"px";
        $(".attr-box").style.height=window.innerHeight-$('.toolbox').offsetHeight+"px";
        $(".page-box").style.width=window.innerWidth-$('.box').offsetWidth-$('.attr-box').offsetWidth+"px";
        // $('.page').style.borderLeftWidth=(parseInt($(".page").style.width)-800)/2+"px";
        // $('.page').style.borderRightWidth=(parseInt($(".page").style.width)-800)/2+"px";
        // $('.page').style.marginLeft=-($('.page').offsetWidth/2)+"px";
        $(".page-box").style.height=window.innerHeight-$('.toolbox').offsetHeight+"px";
        // $('.page').style.borderTopWidth=(parseInt($(".page").style.height)-600)/2+"px";
        // $('.page').style.borderBottomWidth=(parseInt($(".page").style.height)-600)/2+"px";
        
    }
    window.onresize()
}

function load_setting(){
    var remote=require('electron').remote;
    var fs=require('fs');
    var setting=fs.readFileSync('./setting.json')
    window.setting=JSON.parse(setting);
}

function load_editor_theme(){
    var link=document.createElement('link');
    link.setAttribute('rel','stylesheet');
    var theme=setting.theme?setting.theme:'blue';
    link.setAttribute('href','./themes/'+theme+".css");
    document.body.appendChild(link);
}
load_setting();
window.onload = () => {
	new_file();
    load_editor_theme();
    size_init();
    page_init();
    clipboard_init();
    keyboard_init();
}